from flask import Blueprint, request, render_template, session, jsonify, redirect
from config import db, mail
from models.models import User, ma_email
from utils.utils import md5, get_now_data_time
import random
from flask_mail import Message  # 导入邮箱发送程序

import wtforms
from wtforms.validators import Email, Length, EqualTo  # 创建验证类，调入功能验证器


class RegisterFrom(wtforms.Form):  # 验证器验证注册信息格式和验证码对错
    email = wtforms.StringField(validators=[Email(message='邮箱格式错误')])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误")])
    username = wtforms.StringField(validators=[Length(min=1, message='用户名格式错误')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码格式错误')])
    password_confirm = wtforms.StringField(validators=[EqualTo('password', message='两次密码不一致')])

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        ma_model = ma_email.query.filter_by(ma=captcha, email=email).first()
        if not ma_model:
            raise wtforms.ValidationError(message='邮箱验证码错误')
        else:  # 验证码正确，删除数据库保存的验证码信息
            db.session.delete(ma_model)
            db.session.commit()


class ChangePassword(wtforms.Form):  # 修改密码校验器
    email = wtforms.StringField(validators=[Email(message='邮箱格式错误')])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message='验证码格式错误')])
    new_password = wtforms.StringField(validators=[Length(min=6, max=20, message='新密码格式错误')])

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        ma_model = ma_email.query.filter_by(ma=captcha, email=email).first()
        if not ma_model:
            raise wtforms.ValidationError(message='邮箱验证码错误')
        else:  # 验证码正确，删除数据库保存的验证码信息
            db.session.delete(ma_model)
            db.session.commit()


register_service = Blueprint('register_service', __name__)


@register_service.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        form = RegisterFrom(request.form)
        if form.validate():  # 注册信息验证成功,跳转首页
            email = form.email.data
            username = form.username.data
            password = form.password.data
            password = md5(username, password)
            create_time = get_now_data_time()
            user = User(username=username, password=password, email=email, createTime=create_time)
            db.session.add(user)
            db.session.commit()
            return redirect('/login')
        else:  # 注册信息验证失败，跳转回本页面
            print(form.errors)
            return redirect('/register')
    else:
        return render_template('registernew.html')


@register_service.route('/email/ma')  # 邮箱验证码发送
def email_ma():
    email = request.args.get('email')
    # print(email)
    ma = random.randint(1000, 9999)  # 生成伪随机验证码
    message = Message(subject='懒洋洋电商网站注册验证码', recipients=[email], body=f'你的注册验证码是{ma}')
    mail.send(message)  # 发送验证码
    maemail = ma_email(email=email, ma=ma)
    db.session.add(maemail)
    db.session.commit()
    return jsonify({'code': 200, 'message': '', 'data': None})


@register_service.route('/password', methods=['GET', 'POST'])  # 修改密码
def change_password():
    if request.method == 'POST':
        form = ChangePassword(request.form)
        if form.validate():
            new_password = form.new_password.data
            user_id = session.get("user_id")
            user = User.query.filter_by(id=user_id).first()
            new_password = md5(user.username, new_password)
            user.password = new_password
            db.session.add(user)
            db.session.commit()
            return redirect('/login')
        else:
            print(form.errors)
            return redirect('/password')
    else:
        return render_template('new_password.html')